package com.sx.micowell.framework.model

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.example.mvvm.base.data.SingleLiveEvent
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.SPUtils
import com.example.mvvm.until.ToastUtils
import com.example.mvvm.until.Utils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.service.IApiService
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.response.TicketVO
import com.miloyu.modelnet.response.TokenVO
import com.miloyu.modelnet.response.UserAgreementVO
import com.miloyu.modelnet.response.log
import com.sx.micowell.framework.app.AppConstant
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.app.SPKey
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.binding.BindingCommand
import com.sx.micowell.framework.binding.impl.IBindingAction
import com.sx.micowell.framework.entity.AccountBean
import com.sx.micowell.framework.tools.EventInfo
import com.sx.micowell.framework.tools.setDataList
import com.sx.micowell.framework.tools.wxapi.WxEntryRespEvent
import com.sx.micowell.wxapi.WxUtils
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.diffdev.OAuthErrCode
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.*
import kotlin.Comparator


/**
 * @author: YY
 * @time: 2021/8/3
 * @describe TODO
 */
class LoginModel : BaseViewModel() {

    override fun registerRxBus() {
        super.registerRxBus()
        addSubscribe(
            RxBus.getDefault().toObservable(WxEntryRespEvent::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { event ->
                    if (event.type == ConstantsAPI.COMMAND_SENDAUTH) {
                        LogUtils.d("微信登录 ${event.extra}")
                        loginWxCode.set(event.extra)
                        login(true)
                    }
                }
        )

    }

    // 手机号码
    var phoneNumber = ObservableField("")

    // 登录密码
    var loginPassword = ObservableField("")

    // 微信登录code
    var loginWxCode = ObservableField("")

    // 登录状态
    var loginStateEvent: SingleLiveEvent<TokenVO> = SingleLiveEvent()

    // 密码开关
    var pwdSwitchEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()

    // 微信二维码
    var wxQrDataEvent: SingleLiveEvent<TicketVO> = SingleLiveEvent();


    // 忘记密码
    val forgetPwdOnClickCommand = BindingCommand<Any>(IBindingAction {
        RouteManager.getInstance().intentRegisterToForgetPwd(1)
    })

    // 登录
    val loginOnClickCommand = BindingCommand<Any>(IBindingAction {
        login()
    })


    // 微信登录
    val loginWxOnClickCommand = BindingCommand<Any>(IBindingAction {
        if (AppConstant.DEVICE_TYPE) {
            val wxPay = WxUtils()
            wxPay.auth()
        } else {
            context.startContainerActivity(
                RouteManager.getInstance().getWxQRCodeFragment().javaClass.canonicalName
            )
        }
    })


    @SuppressLint("CheckResult")
    fun login(wxScan :Boolean=false) {
        "登录phoneNumber${phoneNumber.get().toString()}".log()
        "登录loginPassword${loginPassword.get().toString()}".log()
        "登录loginWxCode${loginWxCode.get().toString()}".log()
        if (!wxScan) {
            if (TextUtils.isEmpty(phoneNumber.get())) {
                ToastUtils.showShort("请输入账号！")
                return
            }
            if (TextUtils.isEmpty(loginPassword.get())) {
                ToastUtils.showShort("请输入密码！")
                return
            }
            loginWxCode.set("")
        }
        addSubscribe(
            HttpClient.instance.create(IApiService::class.java)
                .login(
                    phoneNumber.get().toString(),
                    loginPassword.get().toString(),
                    loginWxCode.get().toString()
                )
                .doOnSubscribe { ui.showDialog("正在登录...") }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<TokenVO>() {

                    override fun success(data: TokenVO?, msg: String?) {
                        ui.hideDialog()
                        if (data?.isPhone == false) {
                            ToastUtils.showShort("登录成功")
                            SPUtils.getInstance().put(SPKey.SP_TOKEN, data.token)
                            SPUtils.getInstance().put(SPKey.SP_PHONE, phoneNumber.get().toString())
                            saveAccount(
                                phoneNumber.get().toString(),
                                loginPassword.get().toString(), data.token
                            )
                        }
                        loginStateEvent.value = data

                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        LogUtils.d("$errorMsg")
                        ToastUtils.showShort("$errorMsg")
                        ui.hideDialog()
                    }

                })
        )

    }

    fun saveAccount(phone: String, pwd: String, token: String) {
        val accountBean = AccountBean(phone, pwd, token)
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(SPKey.SP_ACCOUNT))) {
            val array: Array<AccountBean> = Gson().fromJson(
                SPUtils.getInstance().getString(SPKey.SP_ACCOUNT), Array<AccountBean>::class.java
            )
            val list = array.toMutableList()
            list.add(0, accountBean)
            setDataList(SPKey.SP_ACCOUNT, list.distinct())
        } else {
            val classTests = mutableListOf<AccountBean>()
            classTests.add(accountBean)
            setDataList(SPKey.SP_ACCOUNT, classTests)
        }
    }

    fun getSdkTicket() {
        addSubscribe(HttpClient.instance.apiService
            .getSdkTicket()
            .doOnSubscribe { ui.showDialog("正在加载...") }
            .compose(RxUtils.compose())
            .subscribeWith(object : ApiResponse<TicketVO>() {

                override fun success(data: TicketVO?, msg: String?) {
                    ui.hideDialog()
                    wxQrDataEvent.value = data
                }

                override fun onFail(e: Throwable?, errorMsg: String?) {
                    LogUtils.d("$errorMsg")
                    ui.hideDialog()
                }

            })
        )
    }


    //用户协议数据
    var agreementEvent: SingleLiveEvent<UserAgreementVO> = SingleLiveEvent()

    /**
     * 用户协议
     */
    fun userAgreement() {

        addSubscribe(
            HttpClient.instance.apiService
                .userAgreement()
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<UserAgreementVO>() {

                    override fun success(data: UserAgreementVO?, msg: String?) {
                        ui.hideDialog()
                        LogUtils.d("userAgreement: ${data?.userAgreement}")
                        agreementEvent.value = data
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                    }

                })
        )
    }
}



